package com.xju.subjectsystem.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

/**
 * -*- coding:utf-8 -*-
 *
 * @projectName: Subjectsystem
 * @package: com.xju.subjectsystem.utils
 * @className: JwtUtil
 * @author: Eiard
 * @description: DONE : Jwt工具类
 * @date: 2024-12-04 11:47
 */
public class JwtUtil {


    /**
     * SECRET_KEY_BYTES   密钥 Bytes
     * SECRET_KEY         密钥
     * EXPIRATION_TIME    过期时间
     */

    private static final byte[] SECRET_KEY_BYTES = new byte[]{
            (byte) 0xF3, (byte) 0x2D, (byte) 0x6B, (byte) 0x59, (byte) 0xE4, (byte) 0x5C, (byte) 0x11, (byte) 0xE0,
            (byte) 0xAE, (byte) 0x99, (byte) 0xA2, (byte) 0xC5, (byte) 0x84, (byte) 0x67, (byte) 0xFE, (byte) 0x38,
            (byte) 0x1C, (byte) 0x4B, (byte) 0x77, (byte) 0xAD, (byte) 0xD7, (byte) 0x8A, (byte) 0xE9, (byte) 0x14,
            (byte) 0x8E, (byte) 0x5F, (byte) 0x3D, (byte) 0xBB, (byte) 0x6E, (byte) 0x17, (byte) 0x9D, (byte) 0x2A
    };
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET_KEY_BYTES);
    private static final long EXPIRATION_TIME = 12 * 60 * 60 * 1000;


    /**
     * @methodName: generateToken
     * @package: com.xju.subjectsystem.utils
     * @description: DONE : 生成令牌
     * @author: Eiard
     * @date: 2024-12-06 17:56
     * @param: claims   自定义信息
     * @return: String  令牌
     */
    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .signWith(SECRET_KEY)
                .claims(claims)
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .compact();
    }

    /**
     * @methodName: parseToken
     * @package: com.xju.subjectsystem.utils
     * @description: DONE : 解析令牌
     * @author: Eiard
     * @date: 2024-12-06 17:57
     * @param: token    令牌
     * @return: Claims  自定义信息
     */
    public static Claims parseToken(String token) throws Exception {
        try {
            return Jwts.parser()
                    .verifyWith(SECRET_KEY)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (Exception e) {
            throw new Exception("无效的JWT令牌", e);  // 捕获异常并抛出更友好的错误信息
        }
    }

}
